import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zootix/models/zt_block.model.dart';
import 'package:zootix/apis/zt-api.dart' as Api;
import 'package:zootix/util/zt_convert.dart';
import 'package:zootix/util/zt_loading_util.dart';
import 'package:zootix/util/zt_snack_bar.util.dart';

import 'zt_im_chat.store.dart';

class ZtBlockStore extends GetxController {
  static ZtBlockStore get to => Get.find();
  final refreshController = RefreshController();
  RxList<ZtBlockModel> blockList = RxList<ZtBlockModel>([]);
  Future<ZtBlockStore> init() async {
    await getBlockList();
    return this;
  }

  Future<void> getBlockList() async {
    final response = await Api.getBlockList();
    if (response.data != null) {
      blockList.assignAll(toList(response.data['data'])
          .map((e) => ZtBlockModel.fromJson(e))
          .toList());
      refreshController.refreshCompleted();
    }
  }

  Future<void> unblock(String userId, int index) async {
    showCupertinoDialog(
        context: Get.context!,
        builder: (_) => CupertinoAlertDialog(
              title: const Text('Are you sure you want to unblock?'),
              actions: <Widget>[
                CupertinoDialogAction(
                  child: const Text('Cancel'),
                  onPressed: () {
                    Get.back(closeOverlays: true);
                  },
                ),
                CupertinoDialogAction(
                  child: const Text('Confirm'),
                  onPressed: () async {
                    Get.back(closeOverlays: true);
                    ZtLoadingUtil.show(status: 'Unblocking...');
                    try {
                      final response = await Api.unblock(int.parse(userId));
                      if (response.data != null && response.data['success']) {
                        blockList.removeAt(index);
                        blockList.refresh();
                        await ZtLoadingUtil.dismiss();
                        await ZtSnackBarUtil().success('Unblock successfully');
                        // 1. remove from IM block list. then will get the msg.
                        await ZtImChartStore.to
                            .removeFromBlacklist(Get.arguments['userId']);
                      }
                    } catch (e) {
                    } finally {
                      ZtLoadingUtil.dismiss();
                    }
                  },
                ),
              ],
            ));
  }
}
